package com.hdu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hdu.entity.Menu;
import com.hdu.mapper.MenuMapper;
import com.hdu.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 菜单实体类 服务实现类
 * </p>
 *
 * @author xiaobai
 * @since 2024-05-21
 */
@Service
@RequiredArgsConstructor
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    private final MenuMapper menuMapper;

    /**
     * 获取所有菜单信息
     */
    @Override
    public List<Menu> getAllUserInfo(String menuAssign) {
        return getUserInfo("", menuAssign);
    }

    public List<Menu> getUserInfo(String pid, String menuAssign) {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        wrapper.eq("pid", pid);
        List<Menu> menuList = list(wrapper);
        for (Menu menu : menuList) {
            menu.setSelect(menuAssign.contains(menu.getId()));
            List<Menu> temp = getUserInfo(menu.getId(), menuAssign);
            menu.setChildren(temp);
        }
        return menuList;
    }

    /**
     * 新增菜单
     */
    @Override
    public void append(Menu menu) {
        StringBuilder id = new StringBuilder(menu.getPid());
        for (int i = 1; i < 10; i++) {
            id.replace(menu.getLevel() - 1, menu.getLevel(), String.valueOf(i));
            if (getById(id.toString()) == null) {
                menu.setId(id.toString());
                break;
            }
        }
        menuMapper.insert(menu);
    }
}

